package com.alibaba.middleware.hsf.guide.serial.hessian.comparator;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Comparator;
import java.util.TreeMap;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.taobao.hsf.com.caucho.hessian.io.AbstractHessianInput;
import com.taobao.hsf.com.caucho.hessian.io.AbstractHessianOutput;
import com.taobao.hsf.com.caucho.hessian.io.Hessian2Input;
import com.taobao.hsf.com.caucho.hessian.io.Hessian2Output;

/**
 * <pre>
 * 验证Hessian不支持同名字段的父子类型序列化（均会使用父类字段）
 * 
 * 序列化时，按照childValue、fatherValue的方式进行的序列化
 * 但是反序列化是，按照childValue和fatherValue分别给子类的filed字段进行连续赋值，最终以fatherValue为结果
 * </pre>
 * 
 * @author weipeng2k 2015年10月8日 下午4:56:43
 */
public class HessianSerial {
    
    static File file;
    
    @BeforeClass
    public static void createFile() {
        try {
            file = File.createTempFile("hessianserial", "dat");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    @Test
    public void serial() throws Exception {
        TreeMap<String, String> map = new TreeMap<String, String>(new Comparator<String>() {
            
            @Override
            public int compare(String o1, String o2) {
                return -o1.compareTo(o2);
            }
        });
        
        for (int i = 0; i < 10; i++) {
            map.put(String.valueOf(i), String.valueOf(i));
        }
        
        System.out.println(map);
        
        AbstractHessianOutput out = new Hessian2Output(new FileOutputStream(file));
        out.writeObject(map);
        out.flush();
    }
    
    @SuppressWarnings("unchecked")
    @Test
    public void deserial() throws Exception {
        AbstractHessianInput in = new Hessian2Input(new FileInputStream(file));
        TreeMap<String, String> cl = (TreeMap<String, String>) in.readObject();
        System.out.println(cl);
    }
    
    @AfterClass
    public static void removeFile() {
        file.delete();
    }
}
